package top.huxy.boot.config.argumentResolver;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import top.huxy.boot.config.Constant;
import top.huxy.boot.exception.NoCredentialsException;
import top.huxy.boot.exception.RequestAbortedException;
import top.huxy.boot.model.entity.Admin;

import javax.servlet.http.HttpServletRequest;

/**
 * @Classname AdminArgumentResolver
 * @Description AdminArgumentResolver
 * @Date 2021/8/30 19:25
 * @Created by huxy
 */
@Slf4j
public class AdminArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType().isAssignableFrom(Admin.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        if (request == null) {
            log.debug("这里不应该是null");
            throw new RequestAbortedException("请求错误");
        }

        Object admin = request.getAttribute(Constant.ADMIN_ATTRIBUTE_NAME);
        if (admin == null) {
            throw new NoCredentialsException("拒绝访问");
        }
        if (admin instanceof Admin) {
            return admin;
        } else {
            throw new NoCredentialsException("请求被拦截");
        }
    }
}
